import 'package:flutter/material.dart';
import 'package:flutter_bilibili/http/dao/login_dao.dart';
import 'package:flutter_bilibili/util/business_util.dart';
import 'package:flutter_bilibili/widget/login_effect.dart';
import 'package:flutter_bilibili/widget/login_input.dart';
import 'package:flutter_bilibili/widget/primary_button.dart';
import 'package:flutter_bilibili/widget/top_app_bar.dart';

/// 登录页面
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  late bool protect = false;
  bool btnEnable = false;
  late String username;
  late String password;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: topAppBar('登录', '注册', toRegisterPage),
      body: ListView(
        // 使用ListView自适应键盘弹起，防止遮挡
        children: [
          LoginEffect(protect: protect),
          LoginInput(
            '用户名',
            onChanged: (text) {
              username = text;
              checkInput();
            },
          ),
          LoginInput(
            '密码',
            obscureText: true,
            focusChanged: (focus) {
              setState(() {
                protect = focus;
              });
            },
            onChanged: (text) {
              password = text;
              checkInput();
            },
          ),
          Padding(
            padding: const EdgeInsets.all(20),
            child: PrimaryButton(
              '登录',
              enable: btnEnable,
              onPressed: send,
            ),
          )
        ],
      ),
    );
  }

  /// 校验表单是否填写
  void checkInput() {
    if (username.isNotEmpty && password.isNotEmpty) {
      setState(() {
        btnEnable = true;
      });
    } else {
      setState(() {
        btnEnable = false;
      });
    }
  }

  /// 发送请求
  void send() async {
    try {
      var res = await LoginDao.login(username, password);
      if (res != null && res['code'] == 0) {
        toHomePage();
      }
    } catch (e) {
      print(e);
    }
  }
}
